package cn.demo.mq.pubsub.direct;

import com.rabbitmq.client.BuiltinExchangeType;
import com.rabbitmq.client.Channel;
import com.rabbitmq.client.Connection;
import com.rabbitmq.client.ConnectionFactory;

import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.util.concurrent.TimeoutException;

/**
 * 测试1  发布订阅 routing 模式  路由模式队列
 *
 * routingKey消息路由
 * @author Mr.Still
 * @version 1.0.0
 * @date 2021-10-18 14:45
 **/
public class Send {
    //可以不用定义队列  可使用默认的 队列， 用完会删除
    public static String QUEUE_NAME = "ps_fanout";

    //交换机
    public static String EXCHANGE_NAME = "exchange_direct";

    public static void main(String[] args) {
        Connection connection = null;
        Channel channel = null;
        try {
            //1.连接工厂
            ConnectionFactory factory = new ConnectionFactory();
            factory.setHost("8.129.129.84");
            factory.setPort(5672);
            factory.setVirtualHost("/demo");
            factory.setUsername("user");
            factory.setPassword("password");
            //2.创建连接对象
            connection = factory.newConnection();

            //3.创建通道
            channel = connection.createChannel();

            //4.创建交换机
            //交换机是根据routingKey路有消息到指定队列
            channel.exchangeDeclare(EXCHANGE_NAME, BuiltinExchangeType.DIRECT);
            //5.发送消息
            String msg = "info msg";
            //交换机，路由键，自定义参数，消息
            channel.basicPublish(EXCHANGE_NAME,"qaq",null,msg.getBytes(StandardCharsets.UTF_8));
            System.out.println("消息发送成功!");
        } catch (IOException e) {
            e.printStackTrace();
        } catch (TimeoutException e) {
            e.printStackTrace();
        }finally {
            if (null!=channel && channel.isOpen()){
                try {
                    channel.close();
                } catch (IOException e) {
                    e.printStackTrace();
                } catch (TimeoutException e) {
                    e.printStackTrace();
                }
            }
            if (null!=connection&&connection.isOpen()){
                try {
                    connection.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }

    }

}
